

package com.hazelcast.function;

import com.hazelcast.internal.serialization.BinaryInterface;

import java.io.Serial;

final class ComparatorsEx {

    static final ComparatorEx<Comparable<Object>> NATURAL_ORDER = new NaturalOrderComparator();
    static final ComparatorEx<Comparable<Object>> REVERSE_ORDER = new ReverseOrderComparator();

    private ComparatorsEx() {
    }

    @BinaryInterface
    private static final class NaturalOrderComparator implements ComparatorEx<Comparable<Object>> {

        @Serial
        private static final long serialVersionUID = 1L;

        @Override
        public int compareEx(Comparable<Object> left, Comparable<Object> right) {
            return left.compareTo(right);
        }

        @Override
        public ComparatorEx<Comparable<Object>> reversed() {
            return REVERSE_ORDER;
        }

        @Serial
        private Object readResolve() {
            return NATURAL_ORDER;
        }
    }

    @BinaryInterface
    private static final class ReverseOrderComparator implements ComparatorEx<Comparable<Object>> {

        @Serial
        private static final long serialVersionUID = 1L;

        @Override
        public int compareEx(Comparable<Object> left, Comparable<Object> right) {
            return right.compareTo(left);
        }

        @Override
        public ComparatorEx<Comparable<Object>> reversed() {
            return NATURAL_ORDER;
        }

        @Serial
        private Object readResolve() {
            return REVERSE_ORDER;
        }
    }

    @BinaryInterface
    public static final class NullComparator<T> implements ComparatorEx<T> {
        @Serial
        private static final long serialVersionUID = 1L;
        private final boolean isNullFirst;

        NullComparator(boolean isNullFirst) {
            this.isNullFirst = isNullFirst;
        }

        @Override
        public int compareEx(T left, T right) {
            if (left == null) {
                return (right == null) ? 0 : (isNullFirst ? -1 : 1);
            } else
                if (right == null) {
                    return isNullFirst ? 1 : -1;
                } else {
                    return 0;
                }
        }
    }
}
